package git.soulbgm.common.handler;

import git.soulbgm.config.SysConfig;
import git.soulbgm.config.SysInfo;
import git.soulbgm.service.AlarmInfoReport;
import git.soulbgm.utils.StringUtil;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程阻塞处理程序
 *
 * @author SoulBGM
 * @date 2024-09-27
 */
public class ThreadBlockingHandler implements RejectedExecutionHandler {

    private final AlarmInfoReport report;
    private final String namePrefix;

    public ThreadBlockingHandler(AlarmInfoReport report, String namePrefix) {
        this.report = report;
        this.namePrefix = namePrefix;
    }

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        SysInfo config = SysInfo.getConfig();
        BlockingQueue<Runnable> queue = executor.getQueue();
        String alarmContent = StringUtil.format("线程池({})已超出队列阻塞异常，当前情况 核心线程数:{}, 活动线程数数:{}, 完成任务数:{}, 队列容量:{}, 队列剩余容量:{}",
                namePrefix,
                executor.getPoolSize(),
                executor.getActiveCount(),
                executor.getCompletedTaskCount(),
                queue.size(),
                queue.remainingCapacity());
        report.threadBlockingAlarm(config.getNodeCode(), config.getServiceCode(), namePrefix, alarmContent);
    }

}
